package cn.cvs.service;

import cn.cvs.dao.BackendUserDao;
import cn.cvs.dao.DevUserDao;
import cn.cvs.dto.LoginUserDto;
import cn.cvs.entiy.BackendUser;
import cn.cvs.entiy.DevUser;
import cn.cvs.uitis.SessionUils;
import cn.cvs.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class LoginUserService {

    @Autowired
    BackendUserDao backendUserDao;
    @Autowired
    DevUserDao devUserDao;

    public LoginUserVo login(LoginUserDto userDto) {
         LoginUserVo userVo = new LoginUserVo();//把数据存到token里面

        if (userDto.getUserType() == 1) {
            //给LoginUserDto里面的字段存数据
            BackendUser backendUser = new BackendUser();

            backendUser.setUsercode(userDto.getAccount());

            backendUser.setUserpassword(userDto.getPassword());

            List<BackendUser> backendUsers = backendUserDao.queryAllBy(backendUser);

            if (backendUsers == null || backendUsers.size() == 0) {
                throw new RuntimeException("账号密码错误");
            }

            userVo.setUser(backendUsers.get(0));

            StringBuffer stringBuffer = new StringBuffer();

            stringBuffer.append(UUID.randomUUID().toString().replace("-", ""));
            stringBuffer.append("-" + backendUsers.get(0).getUsercode());
            stringBuffer.append("-" + backendUsers.get(0).getId());
            stringBuffer.append("-admin");
            stringBuffer.append("-" + System.currentTimeMillis());
            //将token存到缓存里面
            SessionUils.setToken(stringBuffer.toString(), backendUsers.get(0));

            userVo.setToken(stringBuffer.toString());


            return userVo;
        } else if (userDto.getUserType() == 2) {
            DevUser devUser = new DevUser();
            devUser.setDevcode(userDto.getAccount());
            devUser.setDevpassword(userDto.getPassword());
            List<DevUser> devUsers = devUserDao.queryAllBy(devUser);
            if (devUsers == null || devUsers.size() == 0) {
                throw new RuntimeException("账号密码错误");
            }
            userVo.setUser(devUsers.get(0));

            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(UUID.randomUUID().toString().replace("-", ""));
            stringBuffer.append("-" + devUsers.get(0).getDevcode());
            stringBuffer.append("-" + devUsers.get(0).getId());
            stringBuffer.append("-dev");
            stringBuffer.append("-" + System.currentTimeMillis());
            //将token存到缓存里面
            SessionUils.setToken(stringBuffer.toString(), devUsers.get(0));

            userVo.setToken(stringBuffer.toString());

            return userVo;
        } else {
            throw new RuntimeException("不存在的用户类型");
        }
    }
}
